<template>
  <el-container style="margin: 5px 0 0% 5%;">
    <el-main style="width: 75%;background-color: white;padding: 0 20px 0 20px;">
      <div class="main-box">
        <div style="margin: 5px 5px 5px 10px">
          <label class="course-title">{{courseName}}</label>
        </div>
        <div style="margin-top: 5px;">
          <div style="width: 100%;display: flex; text-align: right">
            <p style="width: 70%"/>
            <!-- <label style="font-size: 15px;color: gray">{{teacherName}}</label> -->
          </div>
          <div style="width: 100%;display: flex; text-align: right">
            <p style="width: 70%"/>
            <div style="text-align: center">
              <el-button style="width: 100px; height: 40px;" type="primary" @click="onFollow">
                {{hasFollow ? '退订':'订阅'}}
              </el-button>
              <el-button style="width: 100px; height: 40px;" type="primary" @click="start()">
                看播
              </el-button>
            </div>
          </div>
        </div>
        <hr class="style-two" style="margin-bottom: 20px; margin-top: 20px">

        <!--<div style="height: 55px; margin-bottom: 20px">-->
          <!--<div style="width: 100%;">-->
            <!--<el-switch-->
              <!--style="margin: 0 5px 0 40px"-->
              <!--v-model="mode"-->
              <!--active-text="屏幕分享"-->
              <!--inactive-text="摄像头推流"-->
              <!--:disabled="play_status==false || isPushing == true">-->
            <!--</el-switch>-->
            <!--<el-button size="mini" :disabled="play_status==false"-->
                       <!--@click="isPushing == false ? (mode == false ? startRTC():pushScreen()):stopPush()">-->
              <!--{{isPushing==false?'开始推流':'停止推流'}}-->
            <!--</el-button>-->
          <!--</div>-->
          <!--<div style="width: 100%;margin-top: 10px">-->
            <!--<template v-if="isPushing === true">-->
              <!--<el-switch-->
                <!--v-model="enableCamera"-->
                <!--inactive-text="打开摄像头/屏幕分享"-->
                <!--active-text="关闭摄像头/屏幕分享"-->
                <!--style="margin: 0 5px 0 40px"-->
                <!--v-on:change="toggleCamera()">-->
              <!--</el-switch>-->
              <!--<el-switch-->
                <!--v-model="enableMic"-->
                <!--inactive-text="关闭麦克风"-->
                <!--active-text="打开麦克风"-->
                <!--style="margin: 0 5px 0 5px"-->
                <!--v-on:change="toggleMic()">-->
              <!--</el-switch>-->
            <!--</template>-->
          <!--</div>-->
        <!--</div>-->
        <div style="text-align: center; display: flex;margin-top: 10px">
          <p style="width: 130px"/>
          <div id="video_wrap"/>
        </div>
      </div>
    </el-main>
    <el-aside style="width: 30%;padding-right: 5%">
      <el-container direction="vertical" style="width: 100%">
       <!-- <el-aside style="width: 100%">
        <div class="top-box">
        <el-container style="margin: 0 0 0 0;padding: 0 0 0 0;" direction="vertical">
        <span style="color: cornflowerblue;font-size: 25px;margin-bottom: 10px">成员管理</span>
        <div class="member-box">
        <div v-for="member in members" style="text-align: center">
        <span style="color: darkgray;font-size: 15px">{{member}}</span>
        </div>
        </div>
        </el-container>
        </div>
        </el-aside>-->
        <el-aside style="width: 100%">
          <div class="bottom-box">
            <el-container style="margin: 0 0 0 0;padding: 0 0 0 0;" direction="vertical">
              <span style="color: cornflowerblue;font-size: 25px;margin-bottom: 10px">消息</span>
              <div class="chat-box">
                <div v-for="msg in msgs" :key="msg" style="text-align: left">
                  <span
                    style="color: darkgray;font-size: 15px;margin: 5px 5px 5px 5px">{{msg.send}}:{{msg.content}}</span>
                </div>
              </div>
            </el-container>
            <div>
              <el-input
                type="textarea"
                :autosize="{minRows: 2, maxRows: 2}"
                placeholder="发表一下评论"
                v-model="imMsg.common.data" @keydown.enter="sendMsg" style="margin-bottom: 5px">
              </el-input>
              <el-button type="primary" @click="sendMsg">发送</el-button>
            </div>
          </div>
          <!--<div id="playerId" class="tcplayer"></div>-->
        </el-aside>
      </el-container>
    </el-aside>
  </el-container>
  <!--<div id="live">-->
  <!--<div class="title">-->
  <!--<ul>-->
  <!--<li><router-link to="/home" class="logo"><img src="../../../static/logo.png"></router-link></li>-->
  <!--<li class="course-name">{{courseName}}(房间号：{{courseId}})</li>-->
  <!--<li style="float: right" v-show="!login"><router-link to="#/login">登陆</router-link></li>-->
  <!--<li style="float: right" class='user' v-show="login">-->
  <!--<img :src="iconUrl">-->
  <!--<p>{{userName}}</p>-->
  <!--</li>-->
  <!--</ul>-->
  <!--</div>-->
  <!--<div>-->
  <!--<button :class="hasFollow ? 'followed' : 'follow'" @click="() => {this.hasFollow = !this.hasFollow}">{{hasFollow ? '退订': '订阅'}}</button>-->
  <!--<button :class="hasFollow ? 'followed':'follow'" @click="quitClassroom">{{'退出'}}</button>-->

  <!--</div>-->

  <!--<div class="row">-->
  <!--<div class="col-md-12">-->
  <!--<div class="form-row">-->

  <!--</div>-->
  <!--</div>-->
  <!--<div id="video_wrap">-->
  <!--</div>-->
  <!--</div>-->

  <!--<div class="chat-box">-->
  <!--<h2>消息</h2>-->
  <!--<div id="msg-area" style="height: 55%; overflow-y: scroll; overflow-x: hidden">-->
  <!--&lt;!&ndash; <div class="chat-area" v-for="(msg, index) in msgs" :key=index>{{msg.name}}：{{msg.msg}}</div> &ndash;&gt;-->
  <!--<ul class="im-log-box">-->
  <!--<li v-for="msg in msgs" :key=msg>-->
  <!--<span class="send">{{msg.send}}</span>-->
  <!--<span class="content">{{msg.content}}</span>-->
  <!--</li>-->
  <!--</ul>-->
  <!--</div>-->
  <!--<hr>-->
  <!--<div>-->
  <!--<textarea id = "inputTextArea" class="input-area" wrap="hard" placeholder="发表一下评论" v-model="imMsg.common.data" @keydown.enter="sendMsg"></textarea>-->
  <!--<input type="button" value="发送" @click="sendMsg"/>-->
  <!--</div>-->
  <!--</div>-->
  <!--<div id="playerId" class="tcplayer"></div>-->
  <!--</div>-->
</template>

<script>
import {TcPlayer} from 'tc-player-plus'

export default {
  name: 'courseclass',
  data () {
    return {
      // sdk用
      account: '',
      userID: this.account,
      sdkAppId: 1400234803,
      userSig: '',
      nickName: this.userId,
      roomInfo: '',
      roomID: 27840526,
      isTeacher: false,
      // users: TEST_ACCOUNT.users,
      msgs: [],

      imMsg: {
        common: {},
        custom: {}
      },

      boardData: {
        data: {
          current: null,
          list: []
        },
        page: {
          current: 0,
          total: 0
        }
      },

      remoteVideos: {},
      boardFileGroup: [], // 白板文件组
      currentFile: null, // 当前文件

      // 课程名称
      courseName: '',
      // 课程Id
      courseId: '',
      // 学生姓名（昵称）
      stuName: 'stuxxx',
      // 是否订阅
      hasFollow: false,
      // 播放器
      player: null,
      // 输入框中的临时文字
      temp_text: ''
    }
  },
  watch: {
    // 当msgs中的内容改变时将滚轮滚到最后
    msgs: {
      handler (newV, oldV) {
        setTimeout(
          () => {
            var div = document.getElementById('msg-area')
            div.scrollTop = div.scrollHeight
          }, 10)
      },
      deep: true
    }
  },
  methods: {
    /**
       * 获取userSig
       */
    // findUserSig () {
    //   console.log(this.users)
    //   console.log(this.sdkAppId)
    //   var userSig = null
    //   for (var i = 0, len = this.users.length; i < len; i++) {
    //     if (this.account === this.users[i].userId) {
    //       userSig = this.users[i].userToken
    //       break
    //     }
    //   }
    //   return userSig
    // },

    showErrorTip (title, time) {
      // this.$toasted.error(title, {
      // alert(title, {
      this.$message.success(title, {
        position: 'top-right',
        duration: time || 2000
      })
    },

    showTip (title, time) {
      // this.$toasted.show(title, {
      // alert(title, {
      this.$message.success(title, {
        position: 'top-' +
        'right',
        duration: time || 2000
      })
    },

    start () {
      this.createSig()
      // console.log('xxxx  ' + this.userSig)
      if (!this.roomID) {
        this.showErrorTip('房间号不能为空')
        return
      }
      // this.step = 'second';
      this.init()
    },

    init () {
      this.initData()
      this.tic = null
      this.tic = new TIC({})
      this.tic.init(this.sdkAppId, res => {
        if (res.code) {
          this.showErrorTip('初始化失败，code:' + res.code + ' msg:' + res.desc)
          alert('加载Tic失败')
        } else {
          this.showTip('初始化成功')
          this.Tlogin()
        }
      })
    },

    initData () {
      this.msgs = [],
      this.imMsg = {
        common: {
          data: '',
          toUser: ''
        },
        custom: {
          data: '',
          toUser: ''
        }
      }
    },

    // 登录
    Tlogin () {
      this.tic.login({
        userId: this.account,
        // userSig: this.findUserSig(this.account)
        userSig: this.userSig
      }, (res) => {
        if (res.code) {
          this.showErrorTip('登录失败')
          console.error(res)
        } else {
          this.showTip('登录成功')

          // 增加事件监听
          this.addTICMessageListener()
          this.addTICEventListener()
          this.addTICStatusListener()

          this.joinClassroom()
        }
      })
    },

    joinClassroom () {
      // console.log(this.roomID)
      this.roomID && this.tic.joinClassroom(this.roomID, {}, {
        id: 'paint_box',
        boardContentFitMode: 2
      }, res => {
        if (res.code) {
          this.showErrorTip('加入课堂失败')
          console.error(res)
          // this.step = 'first';
        } else {
          this.showTip('加入课堂成功')
          // window.teduBoard = this.teduBoard = this.tic.getBoardInstance();
          // this.initBoardEvent();

          window.TRTC = this.TRTC = this.tic.getWebRTCInstance()
          this.initTRTCEvent()
        }
      })
    },

    initTRTCEvent () {
      this.TRTC.on('onRemoteStreamUpdate', (data) => {
        var userVideoEl = document.getElementById(data.videoId)
        if (!userVideoEl) {
          userVideoEl = document.createElement('video')
          userVideoEl.id = data.videoId
          userVideoEl.class = 'col-md-1'
          document.querySelector('#video_wrap').appendChild(userVideoEl)
        }
        userVideoEl.autoplay = true
        userVideoEl.playsinline = true
        userVideoEl.srcObject = data.stream

        this.showTip('WebRTC接收到远端流')
      })

      this.TRTC.on('onRemoteStreamRemove', (data) => {
        var userVideoEl = document.getElementById(data.videoId)
        if (userVideoEl) {
          userVideoEl.remove()
        }
        this.showTip('WebRTC 远端流断开')
      })

      this.TRTC.on('onWebSocketClose', (data) => {
        this.showTip('WebRTC WebSocket 断开')
      })

      this.TRTC.on('onRelayTimeout', (data) => {
        this.showTip('WebRTC 超时')
      })

      this.TRTC.on('onStreamNotify', (data) => {
        // console.log('==================== onStreamNotify==', data)
      })
    },

    /**
       * 退出课堂
       */
    quitClassroom () {
      this.tic.quitClassroom(res => {
        if (res.code) {
          this.showErrorTip('退出课堂失败')
          console.error(res)
        } else {
          this.step = 'first'
          this.showTip('退出课堂成功')
        }
      })
    },

    /**
     * 销毁课堂
     */
    destroyClassroom () {
      this.tic.destroyClassroom(this.roomID, res => {
        if (res.code) {
          this.showErrorTip('销毁课堂失败')
          console.error(res)
        } else {
          this.step = 'first'
          this.showTip('销毁课堂成功')
        }
      })
    },

    /**
       * 增加IM消息监听回调
       */
    addTICMessageListener () {
      this.tic.addTICMessageListener({

        /**
           * 收到C2C文本消息
           * @param fromUserId    发送此消息的用户id
           * @param text        收到消息的内容
           * @param textLen      收到消息的长度
           */
        onTICRecvTextMessage: (fromUserId, text, textLen) => {
          this.msgs.push({
            send: fromUserId + '：',
            content: text
          })
        },

        /**
           * 收到C2C自定义消息
           * @param fromUserId    发送此消息的用户id
           * @param data        收到消息的内容
           * @param dataLen      收到消息的长度
           */
        onTICRecvCustomMessage: (fromUserId, data, textLen) => {
          this.msgs.push({
            send: fromUserId + '：',
            content: data
          })
        },

        /**
           * 收到群文本消息
           * @param fromUserId    发送此消息的用户id
           * @param text        收到消息的内容
           * @param textLen      收到消息的长度
           */
        onTICRecvGroupTextMessage: (fromUserId, text, textLen) => {
          this.msgs.push({
            send: fromUserId + '：',
            content: text
          })
        },

        /**
           * 收到群自定义消息
           * @param fromUserId    发送此消息的用户id
           * @param data        收到消息的内容
           * @param dataLen      收到消息的长度
           */
        onTICRecvGroupCustomMessage: (fromUserId, data, textLen) => {
          this.msgs.push({
            send: fromUserId + '：',
            content: data
          })
        },

        /**
           * 所有消息
           * @param msg  IM消息体
           * @note 所有收到的消息都会在此回调进行通知，包括前面已经封装的文本和自定义消息（白板信令消息除外）
           */
        onTICRecvMessage (msg) {

        }
      })
    },

    // 事件监听回调
    addTICEventListener () {
      this.tic.addTICEventListener({
        onTICMemberJoin: (members) => {
          this.msgs.push({
            send: '群消息提示：',
            content: members.join(',') + '进入课堂'
          })
        },

        onTICMemberQuit: (members) => {
          this.msgs.push({
            send: '群消息提示：',
            content: members.join(',') + '退出课堂'
          })
        },

        onTICClassroomDestroy: () => {
          if (!this.isTeacher) { // 学生处理
            this.quitClassroom()
            this.showTip(`老师解散了课堂`)
          }
        }
      })
    },

    // IM状态监听回调
    addTICStatusListener () {
      this.tic.addTICStatusListener({
        onTICForceOffline: () => {
          alert(`其他地方登录，被T了`)
          // this.step = 'first';
        }
      })
    },

    /**
       * 发送普通文本消息
       */
    sendMsg () {
      if (!this.imMsg.common.data) {
        this.showErrorTip(`不能发送空消息`)
      }

      // C2C 文本
      if (this.imMsg.common.toUser) {
        this.tic.sendTextMessage(this.imMsg.common.toUser, this.imMsg.common.data, function (res) {
          // console.log('===sendTextMessage:', res)
        })
      } else { // 群组 文本
        this.tic.sendGroupTextMessage(this.imMsg.common.data, function (res) {
          // console.log('===sendTextMessage:', res)
        })
      }
      this.imMsg.common.data = ''
    },

    /**
       * 发送自定义消息
       */
    sendCustomGroupMsg () {
      //
      if (this.imMsg.common.toUser) { // C2C 自定义
        this.tic.sendCustomMessage(this.imMsg.common.toUser, this.imMsg.custom.data, function (res) {
          // console.log('===sendCustomGroupMsg:', res)
        })
      } else { // 群组 自定义
        this.tic.sendGroupCustomMessage(this.imMsg.custom.data, function (res) {
          // console.log('===sendCustomGroupMsg:', res)
        })
      }
    },
    createSig () {
      var _this = this

      this.getRequest('/api/live/sig?uid=' + this.user.id).then(resp => {
        if (resp && resp.status == 200) {
          // console.log(resp)
          _this.userSig = resp.data.data
          // console.log('uuuu ' + _this.userSig)
          // console.log(_this.roomID)
        }
      })
    },
    chat_submit (e) {
      e.preventDefault()
      this.temp_text = this.temp_text.trim()
      if (!this.temp_text) {
        return
      }
      this.msgs.push({
        name: this.stuName,
        msg: this.temp_text
      })
      this.temp_text = ''
    },
    onFollow () {
      var api = this.hasFollow ? '/api/course/cancel' : '/api/course/take'
      this.postRequestByJSON(api, {
        sid: this.user.id,
        cid: this.courseId
      }).then((res) => {
        if (res && res.data.code == 200) {
          this.$message.success(res.data.msg)
          this.hasFollow = !this.hasFollow
        } else {
          this.$message.error(res.data.msg)
        }
      })
    }
  },
  mounted () {
    this.getRequest('/api/course/getBookCourse?sid=' + this.user.id + '&cid=' + this.courseId).then((res) => {
      this.hasFollow = !!res.data.data
    })
    // this.courseId = this.$route.query.id
    // setTimeout(() => {
    //   this.player = new TcPlayer('playerId', {
    //     rtmp: 'rtmp://yun.toceansoft.com/live/55222_studyLive_' + this.courseId,
    //     flv: 'http://yun.toceansoft.com/live/55222_studyLive_' + this.courseId + '.flv',
    //     m3u8: 'http://yun.toceansoft.com/live/55222_studyLive_' + this.courseId + '.m3u8',
    //     autoplay: true,
    //     width: 1080,
    //     height: 603,
    //     wording: {
    //       2: '直播未开始',
    //       3: '直播已经结束',
    //       2032: '直播已结束，请等待下次开播',
    //       2048: '请求m3u8文件失败，可能是网络错误或者跨域问题，请刷新重试'
    //     }
    //   })
    // }, 200)
  },
  created () {
    this.courseId = parseInt(this.$route.query.id)
    this.account = this.user.id
    this.stuName = this.user.name
    this.getRequest('/api/course/detail?id=' + this.courseId).then((res) => { this.courseName = res.data.data.title })
    this.roomID = parseInt('201625010' + this.courseId)
    // this.start()
  },
  computed: {
    user () {
      return this.$store.state.user
    }
  }
}
</script>

<style scoped>
  @import url("//imgcache.qq.com/open/qcloud/video/tcplayer/tcplayer.css");

  .course-title {
    font-family: Hiragino Sans GB, Arial, sans-serif;
    color: cornflowerblue;
    font-size: 30px
  }

  .top-box {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 20px auto;
    width: 80%;
    box-sizing: border-box;
    padding: 35px 10px 15px 10px;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    text-align: center;
  }

  .bottom-box {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 20px auto;
    width: 80%;
    box-sizing: border-box;
    padding: 35px 10px 10px 10px;
    /*background: #fff;*/
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    text-align: center;
  }

  .main-box {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 20px auto;
    height: 595px;
    padding: 10px 35px 15px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
  }

  .style-two { /*透明渐变水平线*/
    width: 90%;
    border: 0;
    height: 1px;
    background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0));
  }

  .chat-box {
    border: darkgray solid;
    border-radius: 5px;
    border-width: 1px;
    height: 150px;
    overflow: auto;
    margin-bottom: 10px;
  }

  .tcplayer {
    margin: auto;
    margin-left: 13%;
  }

</style>
